package com.pz.ssoserver.service;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.utils.R;
import com.pz.ssoserver.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginService {
    @Autowired
    private UserFeign userFeign;

    public R singleSingOn(String id, String pwd) {
        try {
            R ans = userFeign.queryMember(id);
            if (ans.getCode() == 0){
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                if(passwordEncoder.matches(pwd, String.valueOf(ans.get("pwd")))){
                    StpUtil.login(id);
                    StpUtil.getSession().set("user", ans.get("data"));
                    SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                    return R.ok(BizCodeEnum.AUTH_LOGIN_SUCCESS.getMsg()).put("token", tokenInfo);
                } else {
                    return R.error(BizCodeEnum.AUTH_LOGIN_FAILED.getCode(), BizCodeEnum.AUTH_LOGIN_FAILED.getMsg());
                }
            }else {
                return R.error(BizCodeEnum.AUTH_LOGIN_FAILED.getCode(), BizCodeEnum.AUTH_LOGIN_FAILED.getMsg());
            }
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getMsg(), BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getCode());
        }
    }
}
